package seque.impl;

import seque.SequeList;
import seque.error.SeqListExceptionIndexOver;

/**
 * @author niann
 * @description
 * @since 2024/8/26 下午8:18
 **/
public class SequeListImpl<E> implements SequeList<E> {

    private Object[] data=new Object[10];
    private int size =0;

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void insert(int index, E e) {
        if (index<0 || index> size +1){
            throw new SeqListExceptionIndexOver("index over:\t" +index);
        }
        if (index == size-1){
            insert(e);
            return;
        }
        for (int i = size-1; i >index; i--) {
            if (size-1>= data.length){
                scale();
            }
            data[i+1]=data[i];
        }
        data[index]=e;
        size++;
    }


    /**
     * 扩容
     */
    private void scale(){
        Object[] newData = new Object[size *2];
        System.arraycopy(data,0,newData,0, size);
        data=newData;
    }
    @Override
    public void insert(E e) {
//       扩容
        if (data.length<=size+1){
            scale();
        }
        data[size]=e;
        size++;
    }

    @Override
    public void delete(int index) {
        if (index<0 || index> size -1){
            throw new SeqListExceptionIndexOver("index over:\t" +index);
        }
        if (size-1>= data.length){
            scale();
        }
        Object[] newData = new Object[size];
        for (int i = 0, j = 0; i < size; i++,j++) {
            if (i==index){
                j--;
                continue;
            }
            newData[j]=data[i];
        }
        data=newData;
        size--;
    }

    @Override
    public E get(int index) {
        if (index<0 || index> size -1){
            throw new SeqListExceptionIndexOver("index over:\t" +index);
        }
        return (E) data[index];
    }

    @Override
    public int find(E e) {
        for (int i = 0; i < size-1; i++) {
            if (data[i].hashCode()==e.hashCode() && data[i].equals(e)){
                return i;
            }
        }
        return -1;
    }

    @Override
    public void clear() {
        size =0;
        data[0]=null;
    }

    @Override
    public String toString() {
        StringBuilder rst = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            rst.append(data[i]).append(",");
        }
        if (size !=0){
            rst.delete(rst.length()-1,rst.length());
        }
        rst.append("]");
        return rst.toString();
    }
}
